<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="名称"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getEmployees">查询</el-button>
				</el-form-item>
			</el-form>
		</el-col>

    <!--列表-->
    <el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="username" label="名字" width="100">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="100">
      </el-table-column>
      <el-table-column prop="headImage" label="头像" width="100">
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="100">
      </el-table-column>
      <el-table-column prop="department.name" label="父部门" min-width="100">
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="warning" size="small" @click="handleRole(scope.$index, scope.row)">设置角色</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--设置权限的弹框-->
    <el-dialog title="设置角色" :visible.sync="setRoleVisible" :close-on-click-modal="false">
      <el-form :model="employeeRole" label-width="80px" ref="saveForm">
        <!--indeterminate 属性用以表示 checkbox 的不确定状态，一般用于实现全选的效果 -->
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div class="checkbox-table" v-for="(p,indexkey) in roles" :key="p.id">
          <template>
            <!--
            一级权限的复选框
            label:就是当前复选框的值
            -->
            <el-checkbox class="check1" style="font-weight: 600;margin-bottom: 15px "
                         v-model='employeeRole.roleId' :label="p.id"
                         @change='handleCheck(1,indexkey)'>
              {{p.name}}
            </el-checkbox>

          </template>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="setRoleVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveEmployeeRole" >提交</el-button>
      </div>
    </el-dialog>

    <!--工具条-->
    <el-col :span="24" class="block">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
          style="float:right;">
      </el-pagination>
    </el-col>

    <el-dialog title="编辑页面" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="名称" prop="username">
          <el-input v-model="saveForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="saveForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="saveForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="manager">
          <el-select v-model="saveForm.department" clearable value-key="id" placeholder="请选择">
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"
            -->
            <el-option
                v-for="item in departments"
                :key="item.id"
                :label="item.name"
                :value="item">
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>


	</section>
</template>

<script>
	// import util from '../../common/js/util'
	// //import NProgress from 'nprogress'
	// import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {

        roles:[],
        checkAll:false,
        isIndeterminate:false,
        employeeRole:{
          employeeId:null,
          roleId:[]
        },
        setRoleVisible:false,
				filters: {
					name: ''
				},
        pageInfo: {
				  rows:[],
          total:0
        },
        query: {
          currentPage: 1,
          pageSize: 10,
          keyword:""
        },

        departments: [],
				total: 0,
				page: 1,
				listLoading: false,
				sels: [],//列表选中列


				saveLoading: false,
				//编辑界面数据


				saveFormVisible: false,//新增界面是否显示
				saveFormRules: {
					username: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//新增界面数据
				saveForm: {
					username: '',
					email: '',
          headImage:'',
          age: null,
					department: {
					  id:null,
            name:''
          }

				}

			}
		},
		methods: {
      saveEmployeeRole(){
        this.$http.post("/employee/role",this.employeeRole)
            .then(result => {
              result = result.data;
              if(result.success){
                this.$message({message: '设置成功!', type: 'success'});
                // 关闭弹框
                this.setRoleVisible = false;
              }else{
                this.$message({message: result.message, type: 'error'});
              }
            })
      },
      // 点击"全选"复选框时,触发的方法
      handleCheckAllChange(val){
        // val:就是当前这个复选框它有没有被选中  true:选中(就是说要将下面的复选框都全部选中)  false:取消选中
        // 如果val=true,就要将所有权限的sn赋值给它们双向绑定的数组,通过双向绑定原则,就可以实现所有的复选框被选中
        this.employeeRole.roleId = val ? this.allRoleIds : [];
        // 取消全选框的那个不确定状态
        this.isIndeterminate = false;
      },
      // 处理选择事件  type 1:一级权限2:二级权限   a：一级权限的索引位置
      handleCheck(type, a=0) {
        // 在已选中的权限列表中，查看是否存在一级权限 >-1 存在  <0 不存在
           // 一级菜单点击
        this.roles[a].map(item => {
          this.employeeRole.roleId.push(item.id)
        })

        // 获取已选中的长度
        let checkedCount = this.employeeRole.roleId.length;
        // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
        this.checkAll = checkedCount === this.allRoleIds.length;
        // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.allRoleIds.length;
      },
      // 点击"设置权限"按钮时,触发的方法
      handleRole(index,row){
        this.setRoleVisible = true;
        // 调用后端的权限树接口,给permissionTree赋值,用来做权限树展示
        this.getRoles();
        // 获取所有的权限sn
        this.getAllRoleId();
        this.getRoleIdByEmployeeId(row.id);
        this.employeeRole.employeeId = row.id;

      },
      getRoleIdByEmployeeId(employeeId){
        console.log("jjj")
        this.$http.get("/employee/id/"+employeeId).then(res=>{
          res=res.data;
          if(res.success){
            console.log("ssi")
            console.log(res.obj);
            this.employeeRole.roleId=res.obj

            let checkedCount = this.employeeRole.roleId.length;
            // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
            this.checkAll = checkedCount === this.allRoleIds.length;
            // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.allRoleIds.length;
          }
        })
      },
      getAllRoleId(){
        this.$http.get("/role/ids")
            .then(result => {
              result = result.data;
              if(result.success){
                // result.resultObj 后端返回的所有的权限sn
                console.log("all")
                console.log(result.obj)
                this.allRoleIds = result.obj;

              }
            })
      },
      getRoles(){
        this.$http.get("/role/list")
            .then(result => {
              result = result.data;
              console.log(result)
              if(result.success){
                // 查询成功,将后端返回的数据赋值给this.permissionTree
                this.roles = result.obj;
                console.log("roles")
                console.log(this.roles)
              }
            })
      },
      
     
			handleCurrentChange(val) {
				this.query.currentPage = val;
				this.getEmployees();
			},
      handleSizeChange(val) {
        this.query.pageSize=val;
        this.getEmployees();
      },
			getEmployees() {
				this.listLoading = true;
				//NProgress.start();

				this.$http.post("/employee",this.query).then(result=>{
          this.listLoading = false;
          if(result.data.success){
            this.pageInfo.rows=result.data.obj.pageList;

            this.pageInfo.total=result.data.obj.total;
          }else {
            this.$message({
              message: '查询失败',
              type: 'info'
            });
          }
        })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
          console.log(row.id);
          this.$http.delete("/employee/"+row.id).then((res) => {
						this.listLoading = false;
						if(res.data.success){

              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.query.currentPage=1;
              this.getEmployees();
            }else {
              this.$message({
                message: '删除失败',
                type: 'info'
              });
            }
						//NProgress.done()
					});
				}).catch(() => {
          this.$message({
            message: '网络出错了',
            type: 'info'
          });
				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.saveFormVisible = true;
        this.getDepartments();
        this.saveForm = row
			},
      getDepartments(){
			  this.$http.get("/department").then(res=>{
          console.log("获取所有部门")
          if(res.data.success){
			      this.departments=res.data.obj;
          }
        })
      },



			//bianji
      saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.$http.put("/employee",this.saveForm).then((res) => {
                console.log(res.data);
                if(res.data.success) {
                  this.$message({
                    message: '提交成功',
                    type: 'success'
                  });
                  this.saveFormVisible = false;
                  this.query.currentPage=1;
                  this.getEmployees();
                }
							});
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
          this.listLoading = true;
          console.log(ids);
          this.$http.patch("/employee",ids).then((res) => {
            this.listLoading = false;
            if(res.data.success){

              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.query.currentPage=1;
              this.getEmployees();
            }else {
              this.listLoading = false;
              this.$message({
                message: '删除失败',
                type: 'info'
              });
            }
            //NProgress.done()
          });
				}).catch(() => {
          this.listLoading = false;
				});
			}
		},
		mounted() {
			this.getEmployees();
		}
	}

</script>

<style scoped>

</style>